package com.ft.turorial.spring.boot.controller;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class SecurityController {
	private static final Logger logger = LoggerFactory.getLogger(SecurityController.class);
	
	//用于获取缓存信息
	@Resource
	private EhCacheManager cacheManager;
	
	@RequestMapping(value="",method=RequestMethod.GET)
    public String defaultIndex(Model model){
		String userName = (String) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("username", userName);
        return "index";
    }
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
    public String loginForm(Model model){
        if(SecurityUtils.getSubject().isAuthenticated()){
        	return "redirect:";
        }
        return "security/login";
    }
	
	/*private String builderLoginRedirect(HttpServletRequest request) {
		String redirectUri=request.getRequestURL().toString();
		StringBuilder s=new StringBuilder();
		s.append(InternalResourceViewResolver.REDIRECT_URL_PREFIX);
		s.append(loginUrl);
		s.append("?redirect_uri=").append(redirectUri);	
		s.append("&client_id=").append(clientId);
		s.append("&response_type=code");
		return s.toString();
	}*/
    @RequestMapping(value="/logout",method=RequestMethod.GET)  
    public String logout(RedirectAttributes redirectAttributes ){ 
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();  
        redirectAttributes.addFlashAttribute("message", "您已安全退出");  
        return "redirect:/login";
    } 

    @RequestMapping("/pages/403")
    public String unauthorizedRole(){
        logger.info("------没有权限-------");
        return "pages/403";
    }
}
